﻿using AutoMapper;
using MediatR;
using S.Archives.Api.Application.Command;
using S.Archives.Infrstructre.InterFace;

namespace S.Archives.Api.Application.CommandHandlers
{
    public class SheepFileUpdateStatePLCommandHandler : IRequestHandler<SheepFileUpdateStatePLCommand, bool>
    {
        private readonly ISheepFileRepository sheepFileRepository;
        private readonly IMapper mapper;
        public SheepFileUpdateStatePLCommandHandler(ISheepFileRepository sheepFileRepository, IMapper mapper)
        {
            this.sheepFileRepository = sheepFileRepository;
            this.mapper = mapper;
        }

        /// <summary>
        /// 批量修改羊只档案状态
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<bool> Handle(SheepFileUpdateStatePLCommand request, CancellationToken cancellationToken)
        {
            bool r = false;

            // 根据传入的羊只耳标列表获取需要修改状态的羊只档案
            var Sheeplist = await sheepFileRepository.GetAllAsync();
            Sheeplist = Sheeplist.Where(x => request.EarTag.Contains(x.EarTag)).ToList();

            if (Sheeplist.Any())
            {
                // 批量更新状态
                foreach (var sheep in Sheeplist)
                {
                    // 修改繁殖状态
                    if (request.Uflag == 1)
                    {
                        sheep.ReproductiveState = request.UState;
                    }
                    // 修改在场状态
                    else if (request.Uflag == 2)
                    {
                        sheep.PresenceState = request.UState;
                    }
                    // 是否死亡
                    else if (request.Uflag == 3)
                    {
                        sheep.IsPassAway = true;
                    }
                    // 是否淘汰
                    else if (request.Uflag == 4)
                    {
                        sheep.IsElimination = true;
                    }

                    // 更新时间
                    sheep.UpdateDate = DateTime.Now;
                }

                // 批量更新羊只档案
                r = await sheepFileRepository.UpdateRangeAsync(Sheeplist);
            }

            return r;
        }
    }
}
